package tg.edu.fhh.demo.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tg.edu.fhh.demo.entity.Course;
import tg.edu.fhh.demo.service.CourseService;
import tg.edu.fhh.demo.web.form.CourseForm;

@Controller
@RequestMapping(value = "/course")
public class CourseController {
	@Autowired
	private CourseService courseService;

	@RequestMapping(value = "/manage")
	public void manage() {

	}
//, method = RequestMethod.POST
	@RequestMapping(value = "/list" )
	@ResponseBody
	public Object list(CourseForm form) {
	Specification<Course> spec = buildSpec(form);
		return courseService.findAll(spec);
	}

	@RequestMapping(value = "/edit")
	public void edit(Integer id, ModelMap modelMap) {
		Course model = new Course();
		if (id != null) {
			model = courseService.findById(id);
		}
		modelMap.put("model", model);
	}
	@RequestMapping(value = "/save" )
	@ResponseBody
	public Object save(CourseForm form) {
		Course model = new Course();
		Integer id = form.getId();
		if (id != null) {
			model = courseService.findById(id);
		}
		BeanUtils.copyProperties(form, model, "id");
		courseService.save(model);
		return "OK";
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(Integer id) {
		courseService.deleteById(id);
		return "OK";
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public void search(CourseForm form, ModelMap modelMap) {
		modelMap.put("model", form);
	}

	@SuppressWarnings("serial")
	private Specification<Course> buildSpec(CourseForm form) {
		Specification<Course> spec = new Specification<Course>() {

			@Override
			public Predicate toPredicate(Root<Course> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String name = form.getName();
				if (StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%" + name + "%"));
				}
				String classHour = form.getClassHour();
				if (classHour!= null) {
					rules.add(cb.like(root.get("classHour").as(String.class), "%" + classHour + "%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

}
